package com.ddtech.business.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.course.entity.Course;
import com.ddtech.business.course.entity.CourseStudyRecord;
import com.ddtech.business.course.mapper.CourseStudyRecordMapper;
import com.ddtech.business.course.query.CourseStudyRecordQuery;
import com.ddtech.business.course.service.CourseService;
import com.ddtech.business.course.service.CourseStudyRecordService;
import com.ddtech.business.course.vo.req.CourseStudyReq;
import com.ddtech.business.task.entity.Task;
import com.ddtech.business.task.entity.TaskCourse;
import com.ddtech.business.task.entity.TaskUser;
import com.ddtech.business.task.mapper.TaskMapper;
import com.ddtech.business.task.service.TaskCourseService;
import com.ddtech.business.task.service.TaskUserService;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 课程学习记录表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class CourseStudyRecordServiceImpl extends ServiceImpl<CourseStudyRecordMapper, CourseStudyRecord> implements CourseStudyRecordService {
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private CourseStudyRecordMapper courseStudyRecordMapper;
    @Autowired
    private CourseService courseService;
    @Autowired
    private TaskCourseService taskCourseService;
    @Autowired
    private TaskUserService taskUserService;

    @Override
    public Object pageList(CourseStudyRecordQuery courseQuery) {
        IPage<Map<String, Object>> page = courseStudyRecordMapper.getScheduleList(courseQuery.populatePage(), courseQuery);
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public void create(CourseStudyReq courseStudyReq) {
        String userId = SecurityUtils.getUserId();
        String courseId = courseStudyReq.getCourseId();
        Integer todoDuration = courseStudyReq.getDuration();
        List<Task> taskList = taskMapper.queryByCourseIdAndUserId(courseId, userId);
        for (Task task : taskList) {
            LocalDateTime endTime = task.getEndTime();
            LocalDateTime now = LocalDateTime.now();
            if (now.isBefore(endTime)) {
                //需要学习的时长
                Course course = courseService.getById(courseStudyReq.getCourseId());
                Integer duration = course.getClassHour();
                CourseStudyRecordQuery courseStudyRecordQuery = new CourseStudyRecordQuery();
                courseStudyRecordQuery.setCourseId(courseId);
                courseStudyRecordQuery.setTaskId(task.getId());
                courseStudyRecordQuery.setUserId(userId);
                CourseStudyRecord courseStudyRecord = this.getOne(courseStudyRecordQuery.autoWrapper());
                if (courseStudyRecord == null) {
                    courseStudyRecord = new CourseStudyRecord();
                    courseStudyRecord.init();
                    courseStudyRecord.setIsFinish(0);
                    courseStudyRecord.setTaskId(task.getId());
                    courseStudyRecord.setTaskName(task.getTaskName());
                    courseStudyRecord.setUserId(userId);
                    courseStudyRecord.setUserName(SecurityUtils.getName());
                    courseStudyRecord.setCourseId(course.getId());
                    courseStudyRecord.setCourseName(course.getCourseName());
                }
                //完成时长
                Integer finishDuration = Optional.ofNullable(courseStudyRecord.getDuration()).orElse(0);
                todoDuration += finishDuration;
                if (todoDuration < duration) {
                    courseStudyRecord.setDuration(todoDuration);
                } else {
                    courseStudyRecord.setDuration(duration);
                    courseStudyRecord.setIsFinish(1);
                }
                //保存学习记录
                this.saveOrUpdate(courseStudyRecord);
                //检查是否完成任务
                this.checkIsFishTask(courseStudyRecord);
            }
        }
    }

    public void checkIsFishTask(CourseStudyRecord courseStudyRecord) {
        LambdaQueryWrapper<TaskCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskCourse::getTaskId, courseStudyRecord.getTaskId());
        queryWrapper.eq(TaskCourse::getCourseId, courseStudyRecord.getCourseId());
        List<TaskCourse> list = taskCourseService.list();
        boolean isFinish = true;
        for (TaskCourse taskCourse : list) {
            LambdaQueryWrapper<CourseStudyRecord> studyRecordQuery = new LambdaQueryWrapper<>();
            studyRecordQuery.eq(CourseStudyRecord::getCourseId, taskCourse.getCourseId());
            studyRecordQuery.eq(CourseStudyRecord::getTaskId, courseStudyRecord.getTaskId());
            studyRecordQuery.eq(CourseStudyRecord::getUserId, SecurityUtils.getUserId());
            CourseStudyRecord record = this.getOne(studyRecordQuery);
            if (record == null || record.getIsFinish() != 1) {
                isFinish = false;
                break;
            }
        }
        if (isFinish) {
            LambdaQueryWrapper<TaskUser> taskUserQuery = new LambdaQueryWrapper<>();
            taskUserQuery.eq(TaskUser::getTaskId, courseStudyRecord.getTaskId());
            taskUserQuery.eq(TaskUser::getUserId, SecurityUtils.getUserId());
            TaskUser taskUser = taskUserService.getOne(taskUserQuery);
            if (taskUser != null) {
                taskUser.setIsFinish(1);
                taskUser.setFinishTime(LocalDateTime.now());
                taskUserService.saveOrUpdate(taskUser);
            }
        }
    }

}
